<template>
	<view class="container">
		<view class="form bg-fff p-tb-sms" style="padding-bottom: 10rpx;">
			<view class="form-item">
				<view class="form-item-txt">
					<view class="left-box" @click="getlocationcity">
						<u-icon class="map-in-icon" name="map" color="#731e1f" size="24"></u-icon>
						<text>{{maplocationtemp.city?maplocationtemp.city:maplocation.city}}</text>
						<u-icon class="nav-in-icon" name="arrow-right" size="18rpx" color="#731e1f"></u-icon>
					</view>
					<view class="right-box">
						<u-search placeholder="请输入地址或自提点名称" :show-action="false" v-model="keyword" @change="search" height="50"></u-search>
						<!-- <view class="searchlist" v-if="subPoisSearch.length>0&&keyword" style="width: 460rpx;">
							<view class="search-txt" style="font-size: 12px;" v-for="(item,index) in subPoisSearch" :key="index" @click="changeAddressInAddressDetailList(item)">{{item.title}}</view>
						</view> -->
					</view>
				</view>
				
				<view v-show="keyword==''">
					<view class="flex u-row-between form-item-box">
						<view class="form-item-label">
							<view class="form-item-active">{{vuex_address==''?maplocation.city:vuex_address}}</view>
						</view>
						<view @click="getlocation" class="form-rebuild">
							<image class="rebuild-avatar" :src="$setting.imageUrl()+'position.png'"></image>
							<text>重新定位</text>
						</view>
					</view>
					<view class="form-address-box">
						<span style="color: #666666;">常用地址</span>
						<span @click="addAddress" class="form-address-box-btn">添加地址</span>
					</view>
					<view class="usualLocation" v-if="addressList&&addressList.length>0&&isExpanded">
						<view class="locationDetail" v-for="(item,index) in addressList" :key="index"
							@click="changeAddressInAddressDetailList(item,0)">{{item.detail}}</view>
					</view>
					<view class="expand-button" @click="toggleExpand">
						<view><span style="color: #666666;" v-show="isExpanded==false"></span></view>
						<view class="e_btn"><u-icon :name="isExpanded?'arrow-up':'arrow-down'" color="#666666" size="28"></u-icon></view>
					</view>
				</view>
				
				<!-- <view class="expand-button" @click="toggleExpand">
					<view><span style="color: #666666;" v-show="isExpanded==false"></span></view>
					<view class="e_btn" v-if="isExpanded">{{ isExpanded ? '收起' : '查看' }}</view>
				</view> -->
				
			</view>

		</view>
		<view class="list chooseSearch">
			<view class="list-title">{{keyword==''?"附近":"搜索到"}}的地址</view>
			<scroll-view scroll-y="true" :style="{height: scrollHeight}">
				<view>
					<view  v-show="keyword!=''">
						<view class="item flex-align-center" v-for="(item,index) in subPoisSearch" :key="index"
							@click="changeAddressInAddressDetailList(item,1)">
							<view class="item-con">
								<view class="item-name"><text v-if="subPoisIndex == index">[当前选择]</text>{{item.title}}
								</view>
								<view class="item-address">{{item.address}}</view>
								<!-- <view class="item-address">{{item._distance}}m</view> -->
							</view>
						</view>
						<view v-if="subPoisSearch.length == 0" style="padding-top: 100rpx;">
							<u-empty text="暂无数据" mode="data"></u-empty>
						</view>
					</view>
					
					<view v-show="keyword==''">
						<view class="item flex-align-center" v-for="(item,index) in subPois" :key="index" 
							@click="changeAddressInAddressDetailList(item,1)">
							<view class="item-con">
								<view class="item-name"><text v-if="subPoisIndex == index">[当前选择]</text>{{item.title}}
								</view>
								<view class="item-address">{{item.address}}</view>
								<!-- <view class="item-address">{{item._distance}}m</view> -->
							</view>
						</view>
						<view v-if="subPois.length == 0" style="padding-top: 100rpx;">
							<u-empty text="暂无数据" mode="data"></u-empty>
						</view>
					</view>
					
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {
		pinyin
	} from '../../common/Convert_Pinyin.js';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				subPoisSearch: [],
				subPois: [],
				subPoisIndex: -1,
				isExpanded: true,
				form: {},
				longitude: 0,
				latitude: 0,
				storeInfo: {},
				warehouseInfo: {},
				mycity: '',
				regionList: [],
				citylist: [],
				Letters: [],
				jumperIndex: 0,
				scrollViewId: "indexed-list-YZ",
				keyword: '',
				addressList: []
			}
		},
		methods: {
			...mapMutations(['setcity', 'setRegionstate', 'setRegionLitterstate', 'setMapAddress', 'cleanMapAddress'])
		},
		watch:{
			"subPois"(){
			}
		},
		computed: {

			searchdata() {
				let schlist = [];
				if (this.keyword) {
					let citylist = this.regionList
					let chidcity = [];
					let outbreak = 0;
					citylist.forEach((item) => {
						if (outbreak == 1) {
							return false;
						}
						if (item.children.length > 0) {
							item.children.forEach((citem) => {
								if (schlist.length >= 10) {
									return false;
								}
								if (citem.label.includes(this.keyword)) {
									schlist.push({
										province: item.label,
										city: citem.label
									});
									if (schlist.length >= 10) {
										schlist.push({
											province: "-",
											city: "......"
										});
										outbreak = 1;
										return false;
									}
								}
							})
						}
					})
				}
				return schlist;
			},
			...mapState(['maplocation', 'regionlist', 'regletters', 'vuex_address','maplocationtemp']),
		},
		onLoad() {
			this.getlocationlist();
			this.$store.commit('settempcity',{province:'',city:''});
		},
		onUnload() {
			getApp().globalData.warehouseInfo = {};
		},
		onShow() {
			this.getHttp();
			console.log(this.$store,'this.store')
		},
		methods: {
			addAddress(){
				uni.navigateTo({
					url: '/pages/mine/address/add',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			getlocation(){
				let self = this;
				uni.showLoading({
					title:'定位中'
				})
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						let latitude = res.latitude
						let longitude = res.longitude
						uni.$u.api.tencentMapLocation(latitude, longitude).then(res => {
							// console.log("address",res);
							// console.log(res.data.result.address_component.province,res.data.result.address_component.city)
							this.$store.commit('cleanMapAddress');
							self.$store.commit('setcity',{province:res.data.result.address_component.province,city:res.data.result.address_component.city});
							self.$store.commit('setloaded');
							uni.showToast({
								title: '定位已获取',
								duration: 1000
							});
							// setTimeout(()=>{
							// 	uni.hideLoading()
							// 	uni.navigateBack({delta:2})
							// }, 300);
							this.subPois = [];
							uni.$u.api.tencentMapLocationEXP(latitude, longitude,'category=280000','1000').then(data => {
								console.log("address result",data);
								this.subPois = this.subPois.concat(data.data.data);
								let sublist = data.data.data;
								if(sublist.length>0){
									let nowdetail = sublist[0].title;
									const { location } = sublist[0]
									this.$store.commit('setMapAddress', {
										address_id: 0,
										address: nowdetail,
										lng: location.lng,
										lat: location.lat,
									});
								}
							})
							// this.search(res.data.result.address_component.street);
						})
					},
					fail: () => {
						console.log('fail location')
						uni.hideLoading()
					}
				});
			},
			search(e) {
				let self = this
				self.keyword = e
				if (uni.$u.test.isEmpty(self.keyword)) {
					// uni.showToast({
					// 	title: "搜索关键字不能为空哦",
					// 	icon: "none"
					// });
					return;
				}
				this.subPoisSearch = [];
				// 指定搜索地区为柳州市
				let region = this.maplocationtemp.city?this.maplocationtemp.city:this.maplocation.city;
				uni.$u.api.tencentMapRegionSearch(region, self.keyword, 'category=280000,210000').then(res => {
					if (res.data.status == 0) {
						console.log(res);
						this.subPoisSearch = this.subPoisSearch.concat(res.data.data);
						this.subPoisSearch.sort((a, b) => a._distance - b._distance);
						console.log(this.subPoisSearch, '重新排序');
					} else if (res.data.status == 310) {
						uni.showToast({
							title: "位置信息错误,请检查是否开启定位",
							icon: "none"
						});
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none"
						});
					}
				});
			},
			toggleExpand() {
				this.isExpanded = !this.isExpanded;
			},
			changeAddressInAddressDetailList(item,ctype=0) {
				console.log(item, ctype)
				if(item['ad_info']){
					item.region = item['ad_info']
					item.address_id = item['id']
					item.detail = item['title']
				}
				console.log(item, item.region.province, item.region.city)
				this.$store.commit('setcity', {
					province: item.region.province,
					city: item.region.city
				});
				let goaddress_id = item.address_id;
				if(ctype==1){
					goaddress_id = 0;
				}
				this.$store.commit('setMapAddress', {
					address_id: goaddress_id,
					address: item.detail,
					lng: ctype === 0 ? item.longitude : item.location.lng,
					lat: ctype === 0 ? item.latitude : item.location.lat,
				});
				
				setTimeout(() => {
					uni.navigateBack({})
				}, 300);
			},
			getAddress() {
				uni.$u.api.getAddress().then(res => {
					this.addressList = res.list;

				})
			},
			getlocationlist(){
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						this.longitude = res.longitude
						this.latitude = res.latitude
						uni.$u.api.tencentMapLocationEXP(this.latitude, this.longitude,'category=280000','1000').then(data => {
							console.log("address result",data);
							this.subPois = this.subPois.concat(data.data.data);
						})
					},
					fail: () => {
						console.log('fail location')
						uni.hideLoading()
					}
				});
			},
			getlocationcity() {
				uni.navigateTo({
					url: './selectcityandprovince'
				})
			},
			inputChange(e) {
				this.keyword = e;
			},
			jump(url) {
				uni.navigateTo({
					url: url
				})
			},
			// async getRegion() {
			// 	let self = this;
			// 	if (self.regionlist.length > 0) {
			// 		let regionList = self.regionlist;
			// 		self.regionList = regionList;
			// 		self.pySort(regionList);
			// 		console.log("get cache region list", self.citylist)
			// 	} else {
			// 		uni.$u.api.getRegion({
			// 			treelv: 1
			// 		}).then(async function(res) {
			// 			let regionList = res.regionData;
			// 			self.regionList = regionList;
			// 			self.$store.commit('setRegionstate', regionList);
			// 			self.pySort(regionList);
			// 		})
			// 	}

			// },
			getHttp() {
				this.getAddress()
				// this.getlocation()
				// this.getRegion();
			},
			changeme(pro, city) {
				// //刷新上一页
				// let pages = getCurrentPages();
				// let prePage = pages[pages.length - 2];
				// console.log(prePage)
				// // #ifndef H5
				// prePage.$vm.Dorefresh();
				// // #endif
				uni.showLoading({
					title: '切换中..',
					mask: false
				});
				this.mycity = city
				this.$store.commit('cleanMapAddress');
				this.$store.commit('setcity', {
					province: pro,
					city: city
				});
				this.$store.commit('setloaded');
				setTimeout(() => {
					uni.hideLoading()
					uni.navigateBack({})
				}, 300);
			},
			async pySort(arrList) {
				var $this = this;
				if (!String.prototype.localeCompare)
					return null;
				var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split(''); //ABCDEFGHJKLMNOPQRSTWXYZ
				var zh = "阿八嚓哒妸发旮哈*讥咔垃痳拏噢妑七呥涩它**穵夕丫帀".split('');
				var result = this.citylist;
				var Letters = this.Letters;
				var curr;
				let currok;
				for (let i = 0; i < letters.length; i++) {
					curr = {
						letter: letters[i],
						data: []
					}; //字母对象，data数据
					currok = 0;
					arrList.forEach((n) => {
						let initial = n.label.charAt(0); //截取第一个字符
						let tbcq = 0; //重庆没弄的
						if (initial == '重') {
							tbcq = 1;
						}
						if (initial == letters[i] || initial == letters[i].toLowerCase()) { //首字符是英文的
							curr.data.push(n);
						} else if (zh[i] !== '*' && $this.isChinese(initial)) { //判断是否是无汉字,是否是中文
							let chinaName = pinyin.getFullChars(initial).charAt(0); //直接使用pinyin中方法
							if (tbcq == 1) {
								chinaName = "C";
							}
							if (chinaName == letters[i] || chinaName == letters[i].toLowerCase()) { //首字符是英文的
								curr.data.push(n);
								if (Letters.indexOf(letters[i]) === -1) {
									Letters.push(letters[i]);
								}
								currok = 1;
							}
						}
						if (letters[i] == '#' && !$this.isChar(initial) && !$this.isChinese(initial)) {
							curr.data.push(n);
							if (Letters.indexOf("#") === -1) {
								Letters.push("#");
							}
							currok = 1;
						}
					})
					if (currok == 1) {
						result.push(curr)
					}
				}

				// this.citylist = result; //citylist 是data中定义的 []
				// console.log(this.citylist)
				// console.log(this.Letters)
			},
			isChinese: function(temp) {
				var re = /[^\u4E00-\u9FA5]/;
				if (re.test(temp)) {
					return false;
				}
				return true;
			},
			isChar: function(char) {
				var reg = /[A-Za-z]/;
				if (!reg.test(char)) {
					return false;
				}
				return true;
			},
			jumper(event, i) {
				this.jumperIndex = event;
				let len = this.citylist[i].data.length;
				if (event == '#') {
					this.scrollViewId = 'indexed-list-YZ';
					return
				}
				if (len > 0) {
					console.log(111);
					this.scrollViewId = 'indexed-list-' + event;
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx 30rpx 0 30rpx;
		
		.chooseSearch {
			margin-top: 10px;
			background: #fff;
			padding: 20px;
		}
		.item-name{
			line-height: 25px;
		}
		.item-con{
			padding: 10px 0px;
		}
		.item-address{
			font-size: 12px;
			color: #6b6b6b;
		}
		.list-title{
			font-size: 14px;
			font-weight: bold;
		}
		.scroll-list {
			height: calc(100vh - 240rpx);
		}

		.map {
			border-radius: 16rpx;
			padding: 32rpx;

			.map-con {
				width: 100%;
				height: 196rpx;
			}

			.map-select {
				// margin-top: 20rpx;
			}
		}

		.right-menu {
			width: 40rpx;
			position: fixed;
			right: -8rpx;
			top: calc(50vh);
			transform: translate(-50%, -50%);

			.letter-item {
				font-size: 24rpx;
				font-family: Verdana, Geneva, Tahoma, sans-serif;
				display: block;
				text-align: center;
				background-color: #e8e8e8;
				color: #000;
				line-height: 40rpx;
				border-radius: 20rpx;
				margin-bottom: 5rpx;
				z-index: 10;

				&.active {
					color: #fff;
					background-color: #BB0024;
					font-weight: bold;
				}
			}
		}

		.form {
			padding: 40rpx 32rpx;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			margin-top: 22rpx;

			&.p-tb-sm {
				padding-top: 20rpx;
				padding-bottom: 20rpx;
			}

			&.p-tb-sms {
				margin-top: 0;
				padding-top: 20rpx;
				padding-bottom: 20rpx;
			}

			.item-list {
				display: flex;
				flex-direction: column;
			}

			.item-title {
				font-size: 28rpx;
				font-weight: bold;
				line-height: 40rpx;
			}

			.item-chid-list {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				padding: 20rpx 0;

				.item-title-chid {
					font-size: 26rpx;
					padding: 10rpx 20rpx;
					margin-right: 25rpx;
					margin-bottom: 15rpx;
					border-radius: 4px;
					font-weight: 500;
					color: #000;
					background-color: #eee;
					border: 1px solid #eee;
				}
			}

			.form-item {
				.form-rebuild{
					font-size: 24rpx;
					color: #BB0024;
					display: flex;
					justify-content: flex-end;
					align-items: center;
					width: 160rpx;
				}
				.rebuild-avatar{
					width: 24rpx;
					height: 24rpx;
					margin-right: 10rpx;
				}
				.form-item-label {
					font-size: 26rpx;
					color: #333333;
					// margin-bottom: 10rpx;
					flex-grow: 1;
					display: flex;
					align-items: center;
					
					
					.form-item-active {
						font-size: 28rpx;
						padding: 0rpx 20rpx 0 0;
						border-radius: 4px;
						font-weight: 500;
						color: #000;
						max-width: 500rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
				.form-item-box{
					margin-bottom: 20rpx;
					line-height: 60rpx;
				}
				.form-address-box{
					border-top: 1rpx solid #eee;
					line-height: 60rpx;
					margin-bottom: 10px;
					display: flex;
					justify-content: space-between;
					.form-address-box-btn{
						color: #2b54e4;
						font-size: 26rpx;
					}
				}
				.form-item-txt {
					// margin-top: 20rpx;
					margin-bottom: 20rpx;
					position: relative;
					display: flex;
					flex-direction: row;
					align-items: center;
					.left-box{
						padding:0 20rpx 0 0;
						width: 180rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.right-box{
						flex-grow: 1;
					}
					.map-in-icon {
						margin-right: 10rpx;
					}
					.nav-in-icon {
						margin-left: 10rpx;
						transform: rotate(90deg);
					}
					.searchlist {
						width: 100%;
						position: absolute;
						top: 70rpx;
						border: 1px solid #eee;
						border-radius: 15rpx;
						background: #fff;
						z-index: 11;

						.search-txt {
							padding-left: 30rpx;
							font-size: 28rpx;
							line-height: 70rpx;
							border-bottom: 1px solid #eee;
						}
					}
				}
				
			}

			.form-item+.form-item {
				margin-top: 20rpx;
			}
		}

		.usualLocation {
			width: 100%;
			background-color: #fff;
			// padding-top: 20rpx;
			// padding-bottom: 20rpx;
			padding-left: 32rpx;
			padding-right: 32rpx;
			display: flex;
			flex-direction: column;
			gap: 10px;

			.locationDetail {
				// margin-bottom: 10px;
				overflow: hidden;
				// white-space: nowrap;
				text-overflow: ellipsis;
			}
		}

		.expand-button {
			padding-left: 32rpx;
			// padding-right: 32rpx;
			display: flex;
			justify-content: center;

			.e_btn {
				color: #2b54e4;
			}
		}
	}
</style>
